package cn.dceast.algorithm.service;

import cn.dceast.algorithm.dao.EyeAiLibraryMapper;
import cn.dceast.algorithm.model.EyeAiLibrary;
import cn.dceast.algorithm.model.TsData;
import cn.dceast.former.dao.EyeModelDataMapper;
import cn.dceast.former.model.EyeModelData;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by yang_ on 2017/7/26.
 */
@Service
public class AlgorithmService {
    @Autowired
    private EyeAiLibraryMapper eyeAiLibraryMapper;
    @Autowired
    private EyeModelDataMapper eyeModelDataMapper;

    public List<EyeAiLibrary> getAlgorithms(Map<String, Object> args) {
        return eyeAiLibraryMapper.getAlgorithms(args);
    }

    public int updataModel(EyeModelData eyeModelData) {
        return eyeModelDataMapper.updateByPrimaryKeySelective(eyeModelData);
    }

    public List<EyeAiLibrary> getCurrentAlgorithms(int id) {
        List<EyeAiLibrary> eyeAiLibraries = new ArrayList<>();
        EyeModelData eyeModelData = eyeModelDataMapper.selectByPrimaryKey(id);
        if (eyeModelData != null) {
            String ModelAlgorithm = eyeModelData.getModelAlgorithm();
            if (!StringUtils.isEmpty(ModelAlgorithm)) {
                String[] ModelAlgorithms = ModelAlgorithm.split(",");
                for (int i = 0; i < ModelAlgorithms.length; i++) {
                    eyeAiLibraries.add(eyeAiLibraryMapper.selectByPrimaryKey(Integer.valueOf(ModelAlgorithms[i])));
                }
            }
            return eyeAiLibraries;
        } else {
            return eyeAiLibraries;
        }

    }

    public List<TsData> getTSColum(String tableName) {
        Map<String, String> temp = eyeAiLibraryMapper.getTSData(tableName);
        Map<String, Object> args = new HashedMap();
        List<TsData> tsDatas = new ArrayList<>();
        args.put("table", tableName);
        for (String key : temp.keySet()) {
            args.put("col", key);
            TsData tsData = eyeAiLibraryMapper.tSDataCol(args);
            tsData.setColName(key);
            tsDatas.add(tsData);
        }
        return tsDatas;
    }

    public List<Map<String, Object>> getAllInputCol(Map<String, Object> args) {
        return eyeAiLibraryMapper.getAllInputCol(args);
    }

    /**
     * 根据输入项生成算法处理表（也是结果表）
     *
     * @param args
     * @return
     */
    @Transactional
    public String doInputCol2Res(Map<String, Object> args) {

        List<Map<String, Object>> temp = eyeAiLibraryMapper.getAllInputCol(args);

        List<String> cols = new ArrayList<>();
        cols.add("state");//结果集状态表
        cols.add("res1");//结果1
        cols.add("res2");
        cols.add("res3");
        //处理表（List<Map(1,2),map(1.3),map(2,2)>）->Map(1,"2,3"),Map(2,2)合并
        Map<String, String> sqlMap = new HashedMap();
        Map<String, String> tableHead = new HashedMap();
        for (Map map : temp) {
            String clounName = map.get("cloumName").toString();//upload列名
            cols.add(clounName);
            tableHead.put(clounName, map.get("valName").toString());
            String tableName = map.get("tableName").toString();
            String sqltemp;
            if (sqlMap.get(tableName) == null) {
                sqltemp = clounName;
            } else {
                sqltemp = sqlMap.get(tableName) + "," + clounName;
            }
            sqlMap.put(map.get("tableName").toString(), sqltemp);
        }

        Map<String, Object> resTab = new HashedMap();
        resTab.put("cols", cols);
        String resTable = "res_data_" + System.currentTimeMillis();
        resTab.put("tableName", resTable);
        eyeAiLibraryMapper.creatResTable(resTab);//生成结果集表
        String tempsql = "select ";
        for (String tableName : sqlMap.keySet()) {
            tempsql += sqlMap.get(tableName) + " ,0 as state from " + tableName;//0为跑算法之前的状态
        }
        List<Map<String, Object>> inputData = eyeAiLibraryMapper.getInputData(tempsql);
        Map<String, Object> insert = new HashedMap();
        insert.put("cols", cols);
        insert.put("tableName", resTable);
        tableHead.put("state", "0");
        tableHead.put("res1", "算法结果1");
        tableHead.put("res2", "算法结果2");
        tableHead.put("res3", "算法结果3");
        insert.put("value", tableHead);//插入表头
        eyeAiLibraryMapper.insertIntoRes(insert);
        for (int j = 0; j < inputData.size(); j++) {
            insert.put("value", inputData.get(j));
            eyeAiLibraryMapper.insertIntoRes(insert);
        }
        return resTable;
    }

    @Transactional
    public void updataModelUploadCloum(List<Map> list) throws Exception {
        for (Map map : list) {
            eyeAiLibraryMapper.updataModelUploadCloum(map);
        }
    }

    public List<Map<String, Object>> getAlgorithmType() {
        return eyeAiLibraryMapper.getAlgorithmType();
    }

    public String getAlgorithmArgs(String aiId) {
        Map<String, Object> temp = eyeAiLibraryMapper.getAlgorithmArgs(aiId);
        String args = temp.get("args").toString();
        return args;
    }

    /**
     * 获取模型的输入项
     *
     * @param modelId
     * @return
     */
    public List<String> getModelInputCol(String modelId) {
        return eyeAiLibraryMapper.getModelInputCol(modelId);
    }

    public int doSetAlgorithmArgs(Map<String, Object> args) {
        return eyeAiLibraryMapper.doSetAlgorithmArgs(args);
    }
    public int updataSetAlgorithmArgs(Map<String, Object> args) {
        return eyeAiLibraryMapper.updataSetAlgorithmArgs(args);
    }

    /**
     * 获取算法设置的参数
     * @param args
     * @return
     */
    public Map<String,Object> getAiArgmap(Map<String, Object> args) {
        return eyeAiLibraryMapper.getAiArgmap(args);
    }
}
